#include <string>
#include <stdio.h>
#include <direct.h>
#include "Database.h"


NumericData::NumericData(char const * name, int initialValue)
{
	mName = new char[strlen(name)];
	strcpy(mName, name);
	mValue = initialValue;
}

NumericData::~NumericData()
{
	delete [] mName;
}

char const * const NumericData::GetName()
{
	return mName;
}

int NumericData::GetValue()
{
	return mValue;
}

void NumericData::SetValue(int newValue)
{
	mValue = newValue;
}

Database::Database(char const * name)
{
	mName = new char[strlen(name)];
	strcpy(mName, name);
	mValues.clear();
}

Database::~Database()
{
	for (int i = 0; i < mValues.size(); i++)
	{
		delete mValues[i];
	}
}

void Database::LoadFromFile(char const * filename)
{
	char temp[100];
	bool done = false;
	int byteRead;
	int space;

	FILE * file = fopen(filename, "r");
	if (file != NULL)
	{
		int index;
		for (;;)
		{
			index = 0;
			for (;;)
			{
				byteRead = fread(&temp[index], 1, 1, file);
				if (byteRead == 0)
				{
					done = true;
					break;
				}
				
				if (temp[index] == ' ')
				{
					space = index;
				}
				if (temp[index] == '\n')
				{
					temp[index] = '\0';
					break;
				}
				index++;
			}

			if (index > 3)
			{
				temp[space] = '\0';
				int value = atoi(&temp[space + 1]);
				SetValue(temp, value);
			}

			if (done == true)
			{
				break;
			}
		}
		fclose(file);
	}
}

int Database::GetValueCount()
{
	return mValues.size();
}

int Database::GetValue(char const * name)
{
	NumericData * data = GetValueData(name);
	if (data == NULL)
	{
		return 0;
	}
	return data->GetValue();
}

NumericData * Database::GetValueData(int index)
{
	if (index < this->GetValueCount() && (index >= 0))
	{
		return mValues[index];
	}
	return NULL;
}

NumericData * Database::GetValueData(char const * name)
{
	for (int i = 0; i < mValues.size(); i++)
	{
		if (strcmp(name, mValues[i]->GetName()) == 0)
		{
			return mValues[i];
		}
	}

	return NULL;
}

void Database::AddValue(NumericData * value)
{
	mValues.push_back(value);
}

void Database::SetValue(char const * name, int value)
{
	NumericData * data = GetValueData(name);

	if (data == NULL)
	{
		data = new NumericData(name, value);
		AddValue(data);
	}
	else
	{
		data->SetValue(value);
	}
}
